package com.example.spring.boot.spring.conf.datasource;

import com.zaxxer.hikari.HikariDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;

import javax.annotation.Priority;
import javax.sql.DataSource;

@Configuration
@EnableConfigurationProperties(MySqldbProperties.class)
public class DataSourceConfig {


    @Bean("mySqlDataSource")
    public    DataSource mySqlDataSource( MySqldbProperties mySqldbProperties) {
        HikariDataSource hikariDataSource =  new com.zaxxer.hikari.HikariDataSource();
        hikariDataSource.setDriverClassName(mySqldbProperties.getDriver());
        hikariDataSource.setUsername(mySqldbProperties.getUsername());
        hikariDataSource.setPassword(mySqldbProperties.getPassword());
        hikariDataSource.setJdbcUrl(mySqldbProperties.getUrl());
        return hikariDataSource;
    }

    @Bean("mySqlSessionFactoryBean")
    public  SqlSessionFactoryBean mySqlSessionFactoryBean(DataSource mySqlDataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean =  new org.mybatis.spring.SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(mySqlDataSource);
        return sqlSessionFactoryBean;
    }


    @Bean("mysqlMapperScannerConfigurer")
    public MapperScannerConfigurer mysqlMapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new  org.mybatis.spring.mapper.MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("mySqlSessionFactoryBean");
        mapperScannerConfigurer.setBasePackage("com.example.spring.boot.repository");
        return mapperScannerConfigurer;
    }
 }
